<template>
  <div class="class-students-container">
    <div class="action-bar">
      <el-button 
        type="primary" 
        @click="showAddStudentDialog"
        :disabled="!hasPermission"
      >
        添加学生
      </el-button>
    </div>
    
    <el-table :data="students" border style="width: 100%" v-loading="loading">
      <el-table-column label="学号" width="120">
        <template #default="{row}">
          <div class="boxed-cell">
            {{ row.id }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="姓名" width="120">
        <template #default="{row}">
          <div class="boxed-cell">
            {{ row.stuName }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="stuScore" label="积分" width="80" sortable>
        <template #default="{row}">
          <el-tag :type="getScoreTagType(row.stuScore)">
            {{ row.stuScore }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="stuStudyTime" label="学习时长(分)" width="150" sortable></el-table-column>
      <el-table-column prop="clock" label="打卡时间" width="120"></el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="viewStudent(scope.row)">详情</el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="removeStudent(scope.row)"
            :disabled="!hasPermission"
          >
            移除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加学生对话框 -->
    <el-dialog 
      v-model="addStudentDialogVisible" 
      title="添加学生到班级" 
      width="70%"
      top="5vh"
      :close-on-click-modal="false" 
    >
      <div class="dialog-content">
        <el-input
          v-model="studentSearch"
          placeholder="输入学生姓名或学号搜索"
          clearable
          style="width: 300px; margin-bottom: 20px;"
          @input="filterStudents"
        />
        
        <el-table 
          :data="filteredStudents" 
          border 
          style="width: 100%"
          v-loading="studentLoading"
          height="60vh"
          @selection-change="handleSelectionChange"
        >
          <el-table-column 
            type="selection" 
            width="55"
            :selectable="checkSelectable"
          ></el-table-column>
          
          <el-table-column label="学号" width="120">
            <template #default="{row}">
              <div class="boxed-cell">
                {{ row.userId }}
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="姓名" width="120">
            <template #default="{row}">
              <div class="boxed-cell">
                {{ row.stuName }}
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="状态" width="120">
            <template #default="{row}">
              <el-tag v-if="isStudentInClass(row.id)" type="success">已添加</el-tag>
              <el-tag v-else type="info">未添加</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <span class="selected-count">已选择 {{ selectedStudents.length }} 名学生</span>
          <div>
            <el-button @click="addStudentDialogVisible = false">取消</el-button>
            <el-button 
              type="primary" 
              @click="batchAddStudents"
              :disabled="selectedStudents.length === 0"
            >
              确认添加
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { classApi } from '@/api/class'
import { useRouter } from 'vue-router'

const props = defineProps({
  classId: {
    type: [String, Number],
    required: true
  },
  hasPermission: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update-count'])

const router = useRouter()

// 数据状态
const loading = ref(false)
const students = ref([])
const addStudentDialogVisible = ref(false)
const studentSearch = ref('')
const allStudents = ref([])
const filteredStudents = ref([])
const selectedStudents = ref([])
const studentLoading = ref(false)

// 加载学生数据 - 使用classApi.getClassStudents
const loadStudents = async () => {
  try {
    loading.value = true
    const response = await classApi.getClassStudents(props.classId)
    students.value = response.data || response
    emit('update-count', students.value.length)
  } catch (error) {
    console.error('加载学生列表失败:', error)
    ElMessage.error('加载学生列表失败')
  } finally {
    loading.value = false
  }
}

// 显示添加学生对话框 - 需要您提供获取所有学生的API
const showAddStudentDialog = async () => {
  try {
    studentLoading.value = true
    addStudentDialogVisible.value = true
    // 这里需要您提供获取所有学生的API
    // allStudents.value = (await studentApi.getAllStudents()) || []
    filteredStudents.value = [...allStudents.value]
  } catch (error) {
    ElMessage.error('获取学生列表失败')
    console.error(error)
  } finally {
    studentLoading.value = false
  }
}

// 辅助函数
const handleSelectionChange = (selection) => (selectedStudents.value = selection)
const checkSelectable = (row) => !students.value.some(s => s.id === row.id)
const isStudentInClass = (studentId) => students.value.some(s => s.id === studentId)
const filterStudents = () => {
  filteredStudents.value = studentSearch.value 
    ? allStudents.value.filter(s => 
        s.stuName.toLowerCase().includes(studentSearch.value.toLowerCase()) ||
        String(s.userId).includes(studentSearch.value)
      )
    : [...allStudents.value]
}

// 批量添加学生 - 需要您提供添加学生到班级的API
const batchAddStudents = async () => {
  if (!selectedStudents.value.length) return
  
  const loadingInstance = ElLoading.service({ text: '添加中...' })
  try {
    const results = await Promise.allSettled(
      selectedStudents.value.map(s => classApi.addStudentToClass(props.classId, s.id))
    )
    const successCount = results.filter(r => r.status === 'fulfilled').length
    if (successCount > 0) {
      ElMessage.success(`成功添加${successCount}名学生`)
      loadStudents()
    }
  } catch (error) {
    ElMessage.error('添加学生失败')
    console.error(error)
  } finally {
    loadingInstance.close()
    addStudentDialogVisible.value = false
    selectedStudents.value = []
  }
}

// 移除学生 - 使用classApi.removeStudentFromClass
const removeStudent = async (student) => {
  try {
    await ElMessageBox.confirm(`确定要移除学生 ${student.stuName} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await classApi.removeStudentFromClass(props.classId, student.id)
    ElMessage.success('移除成功')
    loadStudents()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('移除失败')
      console.error(error)
    }
  }
}

// 查看学生详情
const viewStudent = (student) => {
  router.push(`/student/detail/${student.id}`)
}

// 积分标签类型
const getScoreTagType = (score) => {
  score = Number(score)
  return score >= 90 ? 'success' : score >= 80 ? 'primary' : score >= 60 ? 'warning' : 'danger'
}

// 初始化加载
onMounted(() => {
  loadStudents()
})
</script>

<style scoped>
.class-students-container {
  padding: 20px;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.boxed-cell {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 5px 8px;
  display: inline-block;
  min-width: 60px;
  text-align: center;
  background-color: #f5f7fa;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.dialog-content {
  padding: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.selected-count {
  font-size: 14px;
  color: var(--el-text-color-regular);
}
</style>